﻿namespace DYH.Extensions.CAD.Tools.Cad;

/// <summary>
/// 曲线工具
/// </summary>
public static class CurveTool
{
    /// <summary>
    /// 获取最近点（修复坐标过大的情况）
    /// </summary>
    /// <param name="curve">曲线</param>
    /// <param name="point">点</param>
    /// <returns>最近点坐标</returns>
    /// <exception cref="Exception">获取失败</exception>
    public static Point3d GetClosestPointOnCur(this Curve curve, Point3d point)
    {
        var closestPoint = point;
        for (var i = 0; i < 5; i++)
        {
            try
            {
                closestPoint = curve.GetClosestPointTo(closestPoint, false);
                _ = curve.GetParameterAtPoint(closestPoint);
                return closestPoint;
            }
            catch (Exception)
            {
                // 重试
            }
        }

        throw new Exception("GetClosestPointRepair查找最近点失败");
    }

    /// <summary>
    /// 求最近点的参数
    /// </summary>
    /// <param name="curve">曲线</param>
    /// <param name="point">点</param>
    /// <returns>参数值</returns>
    public static double GetParameterAtClosestPoint(this Curve curve, Point3d point)
    {
        try
        {
            var closestPoint = curve.GetClosestPointOnCur(point);
            return curve.GetParameterAtPoint(closestPoint);
        }
        catch (Exception)
        {
            using var curveClone = curve.CloneEx();
            curveClone.Move(-point.GetAsVector());
            var closestPoint = curveClone.GetClosestPointOnCur(Point3d.Origin);
            return curveClone.GetParameterAtPoint(closestPoint);
        }
    }
}